import { reactive, computed, watch } from 'vue'
import type { PropertyPanelProps, AssigneeConfig, ButtonConfig, ButtonType } from '../types'
import type Modeling from 'bpmn-js/lib/features/modeling/Modeling'
import type { Moddle } from 'bpmn-moddle'
import { useButtonConfig } from './useButtonConfig'

export function useAssigneeConfig(props: PropertyPanelProps) {
  const { buttonTypeOptions } = useButtonConfig()

  // 初始化所有可用按钮
  const initButtons = (): ButtonConfig[] => {
    return buttonTypeOptions.value.map((option) => ({
      id: `btn_${option.value}`,
      name: option.label,
      type: option.value as ButtonType,
      sort: option.sort || 1, // 使用字典中的排序，如果没有则默认为1
      enabled: false,
    }))
  }

  const assigneeConfig = reactive<AssigneeConfig>({
    emptyStrategy: 'specified_user',
    buttons: initButtons(),
    timeoutStrategy: '',
    dueDate: '',
  })

  // 是否显示代办人配置
  const showAssigneeConfig = computed(() => {
    return props.currentElement?.type === 'bpmn:UserTask'
  })

  // 监听当前元素变化
  watch(
    () => props.currentElement,
    (newElement) => {
      // 重置配置
      assigneeConfig.emptyStrategy = 'specified_user'
      assigneeConfig.buttons = initButtons() // 重置按钮状态
      assigneeConfig.timeoutStrategy = ''
      assigneeConfig.dueDate = ''

      if (newElement?.type === 'bpmn:UserTask') {
        const bo = newElement.businessObject
        // 更新基础配置
        assigneeConfig.emptyStrategy = bo.get('flowable:emptyStrategy') || 'specified_user'
        assigneeConfig.timeoutStrategy = bo.get('flowable:timeoutStrategy') || ''
        assigneeConfig.dueDate = bo.get('flowable:dueDate') || '24h'

        // 获取已配置的按钮
        const extensionElements = bo.extensionElements
        if (extensionElements && extensionElements.values) {
          const buttonConfigs = extensionElements.values.filter(
            (item: any) => item.$type === 'flowable:ButtonConfig',
          )

          // 更新已配置按钮的状态
          buttonConfigs.forEach((config: any) => {
            const button = assigneeConfig.buttons.find((btn) => btn.type === config.type)
            if (button) {
              button.enabled = true
              button.name = config.name
              button.sort = config.sort
            }
          })
        }
      }
    },
    { immediate: true },
  )

  // 空审批人策略选项
  const emptyStrategyOptions = [
    { label: '指定成员审批', value: 'specified_user' },
    { label: '自动通过', value: 'auto_pass' },
    { label: '自动拒绝', value: 'auto_reject' },
  ]

  // 处理按钮启用状态变更
  const handleButtonStatusChange = (button: ButtonConfig) => {
    console.log('button-after', button.enabled)
    handleAssigneeChange()
  }

  // 修改处理代办人配置变更函数
  const handleAssigneeChange = () => {
    if (!props.currentElement || !props.modeler) return

    const modeling = props.modeler.get('modeling') as Modeling
    const moddle = props.modeler.get('moddle') as Moddle
    const { emptyStrategy, buttons, timeoutStrategy, dueDate } = assigneeConfig

    // 只保存启用的按钮
    const enabledButtons = buttons.filter((btn) => btn.enabled)
    const buttonElements = enabledButtons.map((button) => {
      return moddle.create('flowable:ButtonConfig', {
        id: button.id,
        name: button.name,
        type: button.type,
        sort: button.sort,
        enabled: button.enabled,
      })
    })

    // 获取或创建扩展元素
    let extensionElements = props.currentElement.businessObject.extensionElements
    if (!extensionElements) {
      extensionElements = moddle.create('bpmn:ExtensionElements', { values: [] })
    }

    // 过滤掉旧的按钮配置
    const otherElements =
      extensionElements.values?.filter((item: any) => item.$type !== 'flowable:ButtonConfig') || []

    // 更新扩展元素
    extensionElements.values = [...otherElements, ...buttonElements]

    // 更新属性
    modeling.updateProperties(props.currentElement, {
      'flowable:emptyStrategy': emptyStrategy,
      'flowable:timeoutStrategy': timeoutStrategy,
      'flowable:dueDate': dueDate ? dueDate.toString() : undefined,
      extensionElements,
    })
  }

  return {
    assigneeConfig,
    showAssigneeConfig,
    emptyStrategyOptions,
    buttonTypeOptions,
    handleAssigneeChange,
    handleButtonStatusChange,
  }
}
